﻿Imports System.Data
Imports Sybase.Data.AseClient

Imports System.IO
Imports System.Text

Imports System.Xml 

imports System.Windows.Media
Imports System.ComponentModel   

Imports Microsoft.Office.Interop.Excel
Imports System.Collections.ObjectModel   



Class CMLiquidezSaldos


Private  lstFondosInter As New List(Of CFondoIntermediario)
Private  fondoEnEdicion As CFondo 



Private Sub grdFondoInter_MouseRightButtonUp(ByVal sender As System.Object , ByVal e As System.Windows.Input.MouseButtonEventArgs) Handles grdFondoInter.MouseRightButtonUp
   
  Dim objDepend As DependencyObject = e.OriginalSource 
  Dim celda As DataGridCell = Nothing 


  Me.grdFondoInter.ContextMenu = Nothing  
  While not objDepend is Nothing 

        If objDepend.GetType().Name = "DataGridCell" then 
           celda = objDepend           
           
           If celda.IsSelected = false  then               
               Me.grdFondoInter.UnselectAllCells () 
               celda.IsSelected = True                                                                                                                                                              
           End If                              

          celda.Focus ()          
          Me.grdFondoInter.ContextMenu = AgregarMenuContextual (1)
             

           Exit While 
        End If

       objDepend = VisualTreeHelper.GetParent (objDepend)   
  End While

 


End Sub

Private Sub grdFondoInter_PreviewKeyDown(ByVal sender As System.Object , ByVal e As System.Windows.Input.KeyEventArgs) Handles grdFondoInter.PreviewKeyDown
    If Keyboard.Modifiers = ModifierKeys.Control andalso e.Key = Key.C Then
       Try           
          If copiarCeldas(Me.grdFondoInter) = False then 
              MessageBox.Show ("El rango de celdas seleccionado no es correcto","Copiar celdas",MessageBoxButton.OK,MessageBoxImage.Exclamation) 
          End If

       Catch ex As Exception
                MessageBox.Show("Error TI500. Error al intentar copiar celdas: " & ex.Message, "Copiado", MessageBoxButton.OK, MessageBoxImage.Error)
       End Try

   End If
   
End Sub

Private Sub mnuCopiar_click(sender As Object, e As RoutedEventArgs)
   
 
 Try
    If copiarCeldas(Me.grdFondoInter) = False then 
       MessageBox.Show ("El rango de celdas seleccionado no es correcto","Copiar celdas",MessageBoxButton.OK,MessageBoxImage.Exclamation) 
    End If
 Catch ex As Exception
            MessageBox.Show("Error TI500. Error al intentar copiar celdas: " & ex.Message, "Copiado", MessageBoxButton.OK, MessageBoxImage.Error)
 End Try
 
End Sub 

Private Function  AgregarMenuContextual(ByVal opcion As Integer) As ContextMenu 
  Dim miMenuContextual     As New ContextMenu
  Dim mnuCopia             As New System.Windows.Controls.MenuItem 
  Dim mnuPegar             As New System.Windows.Controls.MenuItem

 
 mnuCopia.Header = "Copiar"
 miMenuContextual.Items.Add(mnuCopia)
 AddHandler mnuCopia.Click,AddressOf  mnuCopiar_click
 
 Return miMenuContextual 

End Function 

Private function copiarCeldas(ByRef gridDeDatos As DataGrid) As Boolean 


 Try
    
         Dim lstInterAux As  List(Of CFondoIntermediario ) = gridDeDatos.ItemsSource
          

         Dim datos As new system.Text.StringBuilder 
         Dim copiadoCorrecto As Boolean  = True 


         Dim colIni As Integer = Integer.MaxValue   
         Dim rowIni As Integer = Integer.MaxValue  

         Dim colFin As Integer = Integer.MinValue 
         Dim rowFin As Integer = Integer.MinValue       


         Dim i As Integer = 0
         Dim j As Integer = 0


         Dim columnasIndex(gridDeDatos.SelectedCells.Count - 1) As Integer
         Dim renglonesIndex(gridDeDatos.SelectedCells.Count - 1) As Integer

        For Each celda As DataGridCellInfo In gridDeDatos.SelectedCells 

            renglonesIndex(i) = gridDeDatos.Items.IndexOf (CType(celda.Item,CFondoIntermediario ))
            columnasIndex(j) = celda.Column.DisplayIndex           
            i+=1
            j+=1
        Next


           rowIni = renglonesIndex.Min () 
           rowFin = renglonesIndex.Max () 

           colIni = columnasIndex.Min ()
           colFin = columnasIndex.Max ()


         For i = rowIni to rowFin 
            For j = colIni  to colFin 
                If EsSeleccionadaLaCelda(gridDeDatos, i,j) then 
                     datos.Append ( lstInterAux(i)(j).ToString() & vbTab )
                else          
                    copiadoCorrecto = False 
                    GoTo fuera
                End If        
            Next
    
            datos.Remove (datos.Length -1,1)
            datos.Append (vblf)
         Next
 

         datos.Remove (datos.Length -1,1)

 

         fuera:
         If copiadoCorrecto = True then 
            Clipboard.Clear ()
            Clipboard.SetText (datos.ToString () )
            Return true
         else
           Return False  
         End If


 Catch ex As Exception

     Throw ex
     
 End Try




End function

Private function EsSeleccionadaLaCelda(ByRef gridDeDatos As DataGrid,  ByVal indexRow As Integer, ByVal indexCol As Integer ) As Boolean 

Dim row as DataGridRow  = gridDeDatos.ItemContainerGenerator.ContainerFromIndex(indexRow)
Dim cellContent As TextBlock = gridDeDatos.Columns(indexCol).GetCellContent(row)     
 

  Dim objDepend As DependencyObject = cellContent
  Dim celda As DataGridCell = Nothing 

   While not objDepend is Nothing 

        If objDepend.GetType().Name = "DataGridCell" then 
           celda = objDepend           
           
           If celda.IsSelected = True   then                
               Return true
            else
               Return False 
           End If
                                           
        End If

       objDepend = VisualTreeHelper.GetParent (objDepend)   
  End While

  Return False

End Function 

Private Sub seleccionarcelda(ByRef gridDeDatos As DataGrid, ByVal indexRow As Integer, ByVal indexCol As Integer)
  
Dim row as DataGridRow  = gridDeDatos.ItemContainerGenerator.ContainerFromIndex(indexRow)
Dim cellContent As TextBlock = gridDeDatos.Columns(indexCol).GetCellContent(row)     


  Dim objDepend As DependencyObject = cellContent
  Dim celda As DataGridCell = Nothing 


   While not objDepend is Nothing 

        If objDepend.GetType().Name = "DataGridCell" then 
           celda = objDepend           
           
           If celda.IsSelected = false  then                
               celda.IsSelected = True                  
               celda.Focus ()
               Exit While                
           End If
                                           
        End If

       objDepend = VisualTreeHelper.GetParent (objDepend)   
  End While

End Sub


Private Sub CargarSaldosTotales()
Dim negocio As new CLiquidezServicio ()




Try

txtSaldoDisp.Text = negocio.ObtenerImporteTotal (1,lstFondosInter).ToString ("$ ##,##0.00")  
txtOrdenPend.Text  = negocio.ObtenerImporteTotal (2,lstFondosInter).ToString ("$ ##,##0.00")  
txtPendingCash.Text  = negocio.ObtenerImporteTotal (3,lstFondosInter).ToString ("$ ##,##0.00")  
txtPendindAdj.Text  =  negocio.ObtenerImporteTotal (4,lstFondosInter).ToString ("$ ##,##0.00")  
txtSalDecalog.Text  =  negocio.ObtenerImporteTotal (5,lstFondosInter).ToString ("$ ##,##0.00")  

Catch ex As Exception
            MessageBox.Show("Error TI500. Error al intentar calcular los importes totales: " & ex.Message, "Obtener totales", MessageBoxButton.OK, MessageBoxImage.Exclamation)
End Try



End Sub

Private Sub Fondoinver_PropertyChanged(sender As Object, e As PropertyChangedEventArgs)
  
Dim negocio As new CLiquidezServicio ()

Try
    Select Case e.PropertyName

      Case "SalDisponible"
           txtSaldoDisp.Text = negocio.ObtenerImporteTotal (1,lstFondosInter).ToString ("$ ##,##0.00")
      Case "OrdenPend"
           txtOrdenPend.Text  = negocio.ObtenerImporteTotal (2,lstFondosInter).ToString ("$ ##,##0.00")  
      Case "PendingCash"
           txtPendingCash.Text  = negocio.ObtenerImporteTotal (3,lstFondosInter).ToString ("$ ##,##0.00")  
      Case "PendingCashAjust"
           txtPendindAdj.Text  =  negocio.ObtenerImporteTotal (4,lstFondosInter).ToString ("$ ##,##0.00")  
      Case "SaldoDecalogT"
           txtSalDecalog.Text  =  negocio.ObtenerImporteTotal (5,lstFondosInter).ToString ("$ ##,##0.00")  
        
    End Select 

Catch ex As Exception
            MessageBox.Show("Error TI500. Error al intentar calcular los importes totales: " & ex.Message, "Obtener totales", MessageBoxButton.OK, MessageBoxImage.Exclamation)
End Try
        

End Sub

Private Function  ObtenerCelda(ByRef miDataGrid As DataGrid, ByVal indexRow As Integer, ByVal indexCol As Integer  ) As DataGridCell 

Try
      Dim row as DataGridRow  = miDataGrid.ItemContainerGenerator.ContainerFromIndex(indexRow)            
      Dim cellContent As Object  = miDataGrid.Columns(indexCol).GetCellContent(row)     
 
      Dim objDepend As DependencyObject = cellContent
      Dim celda As DataGridCell = Nothing       

       While not objDepend is Nothing 

            If objDepend.GetType().Name = "DataGridCell" then 
               celda = objDepend           
               Return celda                                                      
            End If
           objDepend = VisualTreeHelper.GetParent (objDepend)   
      End While
Catch ex As Exception
    Throw ex
End Try

Return Nothing 
End Function

Public Sub New()                
  InitializeComponent()                        
  Mouse.OverrideCursor = Nothing         
End Sub
 

Private Sub Page_Loaded(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles MyBase.Loaded
        Me.imgRefrescar.Focus  
End Sub


Private Sub btnRefrescar_MouseLeftButtonUp(ByVal sender As System.Object , ByVal e As System.Windows.RoutedEventArgs  ) Handles btnRefrescar.Click  
    Dim negocioLiq As new CLiquidezServicio ()    

     Dim idRegBit As Integer  
 
    Mouse.OverrideCursor = Cursors.Wait 
        
    Try

       idRegBit =  CUtileria.GrabarBitacora ("Saldos","Refresh","Actualiza información")     


       lstFondosInter  = negocioLiq.refrescar (negocioLiq.obtenerFondos (CDefinicionesGrales.TiposFondo.FondoSaldos ) )      
       Me.grdFondoInter.ItemsSource = lstFondosInter 
       Me.grdFondoInter.Items.Refresh ()
       

       CargarSaldosTotales ()

        
        For each fondo As  CFondoIntermediario In  lstFondosInter
            AddHandler  fondo.PropertyChanged, AddressOf Fondoinver_PropertyChanged
        Next


        Me.txtNumRow.Text = lstFondosInter.Count 
        Me.btnExpExcel.IsEnabled = True 


        CUtileria.CompletarRegBitacora (idRegBit )

    Catch ex As Exception         
         Mouse.OverrideCursor = nothing
            MessageBox.Show("Error:" & ex.Message, "Proceso refrescar", MessageBoxButton.OK, MessageBoxImage.Error)

         idRegBit =  CUtileria.GrabarBitacora ("Saldos","Refresh","Error: " & ex.Message)
         CUtileria.CompletarRegBitacora (idRegBit )

    End Try
    
    Mouse.OverrideCursor = Nothing 



End Sub


Private Sub btnExpExcel_Click(ByVal sender As System.Object , ByVal e As System.Windows.RoutedEventArgs ) Handles btnExpExcel.Click  

    Dim xlsAplicacion As _Application
    Dim wbkLibro      As Workbook
    Dim shtHoja       As Worksheet


    Dim regInicial As Integer = 5 
    
    Dim colInicial As Integer = 0 
    Dim colInicialSTR As String  = "A"

    Dim rangoRegFinal As Integer 
    Dim rangoColFinalSTR As String = "F"


    xlsAplicacion  =CUtileria.ExportarAExcel (Me.grdFondoInter,regInicial,colInicial)
    wbkLibro = xlsAplicacion.ActiveWorkbook 
    shtHoja = wbkLibro.Sheets(1)

    'TITULO


    shtHoja.Range ("C3").Value = "Saldos Decalog"
    shtHoja.Range ("C3").Font.Bold = True 
    shtHoja.Range ("C3").Font.Size = 15



 

    rangoRegFinal = Me.grdFondoInter.Items.Count  + regInicial 

    
    shtHoja.Cells(rangoRegFinal + 2, 1).value = "TOTAL"
    shtHoja.Cells(rangoRegFinal + 2, 2).value = Me.txtSaldoDisp.Text 
    shtHoja.Cells(rangoRegFinal + 2, 3).value = Me.txtOrdenPend.Text  
    shtHoja.Cells(rangoRegFinal + 2, 4).value =  Me.txtPendingCash.Text  
    shtHoja.Cells(rangoRegFinal + 2, 5).value =  Me.txtPendindAdj.Text 
    shtHoja.Cells(rangoRegFinal + 2, 6).value =  Me.txtSalDecalog.Text 

   
    'HEADERS
    shtHoja.Range (colInicialSTR & regInicial.ToString & ":" &  rangoColFinalSTR & (regInicial).ToString   ).Font.Bold =True 
    shtHoja.Cells.EntireColumn.AutoFit   
    shtHoja.Cells.EntireRow.AutoFit   

    'TOTALES
    shtHoja.Range (colInicialSTR & (rangoRegFinal + 2).ToString & ":" &  rangoColFinalSTR & ((rangoRegFinal + 2).ToString).ToString).Font.Bold =True 

    shtHoja.Range("B" & (regInicial + 1).ToString & ":" & rangoColFinalSTR & (rangoRegFinal + 2).ToString ).NumberFormat = "#,##0.00###"    
    
End Sub




End Class
